#include <iostream>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>

//return 
void* Thread1(void*)
{
  pid_t tid = syscall(SYS_gettid);
  static long flag = 1;
  printf("thread1->tid:%d\n", (int)tid);
  return (void*)(&flag);
}

//pthread_exit
void* Thread2(void*)
{
  pid_t tid = syscall(SYS_gettid);
  static int flag = 2;
  int i = 0;
  while(true){
    sleep(1);
    printf("thread2->tid:%d\n", (int)tid);
    if(i++ == 2){
      pthread_exit(&flag);
    }
  }
}

//pthread_cancel
void* Thread3(void*)
{
  pid_t tid = syscall(SYS_gettid);
  while(true){
    sleep(1);
    printf("thread3->tid:%d\n", (int)tid);
  }
}

int main()
{
  pthread_t tid;
  void* ret;
  pthread_create(&tid, nullptr, Thread1, nullptr);
  pthread_join(tid, &ret);
  printf("thread1 return,thread tid->%X  thread code: %d\n", tid, *(int*)ret);

  pthread_create(&tid, nullptr, Thread2, nullptr);
  pthread_join(tid, &ret);
  printf("thread2 exit, thread tid->%X  thread code: %d\n", tid, *(int*)ret);

  pthread_create(&tid, nullptr, Thread3, nullptr);
  sleep(4);
  pthread_cancel(tid);
  pthread_join(tid, &ret);
  if(ret == PTHREAD_CANCELED){
    printf("thread3 cancel, thread tid->%X  thread code:PTHREAD_CANCELED\n", tid);
  }
  return 0;
}
